import hotkeys from 'hotkeys-js'
import { type Works, type WindwoMessageEventMap, CollectionOfWorks } from 'shared/types/index'
import { useWindowMessage } from 'shared/message/window'
import type { DisposeOption } from './dispose'
import { initializeSingleDownload } from './single-download'
import { DouyinExtensionTool } from './element'
import tpl from '../assets/import.html?raw'
import { showMessage } from './message'

interface AwemeAuthor {
  uid: string
  sec_uid: string
  /** 用户名 */
  nickname: string
  avatar_thumb: {
    width: number
    height: number
    /** 封面的具体链接 */
    url_list: string[]
  }
}

interface AwemeVideoCover {
  width: number
  height: number
  /** 封面的具体链接 */
  url_list: string[]
}

interface AwemeVideoAddress {
  /** 视频大小 */
  data_size: number
  width: number
  height: number
  url_key: string
  /** 视频的具体链接 */
  url_list: string[]
}

interface AwemeVideo {
  /** 封面 */
  cover: AwemeVideoCover
  /** 播放地址 */
  play_addr: AwemeVideoAddress
  /** 播放地址 */
  play_addr_h264: AwemeVideoAddress
}

interface Aweme {
  aweme_id: string
  /** 标题 */
  item_title: string
  /** 标题 */
  caption: string
  desc: string
  author: AwemeAuthor
  video: AwemeVideo
}

interface CollectionOfWorksResponse {
  aweme_list?: Aweme[]
  has_more: 0 | 1
}

function collectionOfWorksDefault(): CollectionOfWorks {
  return {
    uid: '',
    sid: '',
    name: '',
    avatar: '',
    works: {},
  }
}

export const collectionOfWorks = collectionOfWorksDefault()

function analyzeVideo({ cover, play_addr, play_addr_h264 }: AwemeVideo): Pick<Works, 'cover' | 'video'> {
  const { url_list } =
    ((play_addr?.data_size ?? 0) > (play_addr_h264?.data_size ?? 0) ? play_addr : play_addr_h264) ?? {}
  return { cover: cover?.url_list ?? [], video: url_list ?? [] }
}

const { postMessage } = useWindowMessage<WindwoMessageEventMap>('window')

function sendDataToContentScript() {
  const worksList = Object.keys(collectionOfWorks.works)
  if (worksList.length) {
    postMessage('works', collectionOfWorks)
    showMessage({
      type: 'success',
      message: `已将 ${collectionOfWorks.name} 的 ${worksList.length} 条作品数据发送到后端，请在选项页面查看`,
    })
  } else {
    showMessage({ type: 'warn', message: '当前未匹配到作品数据' })
  }
}

function normalizeName(name: string) {
  return name?.replace(/\n/g, ' ').replace(/\s?(\#|@).+$/, '') || name
}

const disposeListOption: DisposeOption<CollectionOfWorksResponse> = {
  hostname: 'www.douyin.com',
  pathname: '/aweme/v1/web/aweme/post/',
  processor({ response, searchParams }) {
    const count = parseInt(searchParams.get('count')!)
    if (Number.isNaN(count) || count < 5) {
      collectionOfWorks.uid && Object.assign(collectionOfWorks, collectionOfWorksDefault())
      return
    }
    
    const { aweme_list } = response
    if (!aweme_list?.length) return

    const { uid: userId, sec_uid, nickname, avatar_thumb } = aweme_list[0].author
    if (sec_uid !== collectionOfWorks.sid) {
      Object.assign(collectionOfWorks, {
        uid: userId,
        sid: sec_uid,
        name: nickname,
        avatar: avatar_thumb.url_list.pop() ?? '',
        works: {},
      })
    }

    aweme_list.forEach(({ aweme_id, item_title, caption, desc, video }) => {
      collectionOfWorks.works[aweme_id] = {
        id: aweme_id,
        title: item_title || normalizeName(caption || desc),
        ...analyzeVideo(video),
      }
    })
  },
  then() {
    hotkeys('ctrl + alt + s', sendDataToContentScript)
    initializeSingleDownload(collectionOfWorks)

    new DouyinExtensionTool(tpl, {
      import: sendDataToContentScript,
    })
  },
}

export default disposeListOption
